﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace LiveProjectManager.DDD.Services
{
    public class CategoryService : Base.Service<Domains.Category>
    {
        public CategoryService() : base()
        {
        }


        override public ICollection<Domains.Category> getAll(int paginateBy = 0, int page = 1)
        {
            if (paginateBy > 0) {
                if (page <= 0)
                    page = 1;
                return (from c in _repository orderby c.Id select c).Skip(paginateBy * (page - 1)).Take(paginateBy).ToList();
            }
            return (from c in _repository orderby c.Id select c).ToList();
        }


        public bool exists(string myName)
        {
            return (getByName(myName) != null);
        }


        override public Domains.Category getById(long myId)
		{
            ICollection<Domains.Category> myResults = (from c in _repository 
                                                             where c.Id == myId 
                                                             select c).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public Domains.Category getByName(string myName)
        {
            ICollection<Domains.Category> myResults = (from c in _repository
                                                       where c.Name == myName
                                                       select c).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public bool create(
            string myName,
            string myDescription = null,
            bool autoSave = true
        )
        {
            try
            {
                // Category already exists.
                if (exists(myName))
                    return false;

                // Create the new category.
                Domains.Category myNewCategory = new Domains.Category
                {
                    Name = myName,
                    CreatedOn = DateTime.Now
                };
                if (myDescription != null)
                    myNewCategory.Description = myDescription;

                // Insert in repository.
                _repository.Add(myNewCategory);
                if (autoSave)
                    _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        override public bool remove(long myId, bool autoSave = true)
        {
            Domains.Category myCategory = getById(myId);
            if (myCategory == null)
                return false;
            _repository.Remove(myCategory);
            if (autoSave)
                _context.SaveChanges();
            return true;
        }
    }
}